package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.Category;
import com.example.result.JsonResult;
import com.example.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController{   //菜品分类表
    @Autowired
    private CategoryService categoryService;
    //新增菜品分类
    @PostMapping
    public JsonResult save(@RequestBody Category category){
        boolean flag = categoryService.save(category);
        if(!flag){
            throw new RuntimeException("新增失败!");
        }
        return new JsonResult(1,"新增成功");
    }
    //分类分页查询
    @GetMapping("/page")
    public JsonResult page(Integer page,Integer pageSize){
        IPage<Category> iPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(iPage,queryWrapper);
        return new JsonResult(1,"",iPage);
    }
    //删除分类
    @DeleteMapping
    public JsonResult delete(Long id){
        categoryService.delete(id);
        return new JsonResult(1,"删除成功");
    }
    //修改分类
    @PutMapping
    public JsonResult update(@RequestBody Category category){
        boolean flag = categoryService.updateById(category);
        if(!flag){
            throw new RuntimeException("更新失败!");
        }
        return new JsonResult(1,"更新成功");
    }
    //获取菜品分类数据
    @GetMapping("/list")
    public JsonResult list(Category category){
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        return new JsonResult(1,"",list);
    }

}
